import { parentPort } from 'worker_threads';
import crypto from 'crypto';

const port = parentPort;
if (!port) throw new Error('IllegalState');

port.on('message', (msg) => {
  try {
    if (msg.method === 'encrypt') {
      const encrypted = encrypt(msg.key, msg.plainText);
      port.postMessage({ encrypted });
    }
    if(msg.method === 'decrypt') {
      const decrypted = decrypt(msg.key, msg.iv, msg.encrypted);
      port.postMessage({ decrypted });
    }

  } catch (error) {
    console.log('AESWorker 错误：', error);
  }
});


/**
 * 加密数据
 * @param key 密钥
 * @param plainText 明文
 * @returns 加密后的数据
 */
const encrypt = (key: string, plainText: string) => {
  const keyBuffer = Buffer.from(key, 'hex');
  if (keyBuffer.length !== 32) {
    console.log('AESWorker 错误：密钥长度不正确');
    return {
      iv: '',
      encrypted: ''
    };
  }
  const iv = crypto.randomBytes(16); // 初始化偏移量

  const cipher = crypto.createCipheriv('aes-256-cbc', keyBuffer, iv); // 创建加密器实例

  let encrypted = cipher.update(plainText, 'utf8', 'hex'); // 加密
  encrypted += cipher.final('hex');

  return {
    iv: iv.toString('hex'),
    encrypted: encrypted
  };
};

/**
 * 解密数据
 * @param key 密钥
 * @param ivString 偏移量字符串
 * @param encryptedData 加密后的数据
 * @returns 解密后的数据
 */
const decrypt = (key: string, ivString: string, encryptedData: string) => {
  // 从十六进制字符串转换密钥和IV到Buffer。
  const keyBuffer = Buffer.from(key, 'hex');
  const iv = Buffer.from(ivString, 'hex');

  // 检查密钥长度是否正确
  if (keyBuffer.length !== 32) {
    console.log('AESWorker 错误：密钥长度不正确');
    return '';
  }

  // 创建解密器实例
  const decipher = crypto.createDecipheriv('aes-256-cbc', keyBuffer, iv);

  // 解密数据
  let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
  decrypted += decipher.final('utf8');

  console.log('AESWorker 解密后的数据：', decrypted);
  // 返回解密后的数据
  return decrypted;
};
